<?php
class UserMapper extends Mapper{
  const TBL_NAME = 'user';

  public function createUser(UserModel $user){
    $st = $this->db->prepare('INSERT INTO '.self::TBL_NAME.' (name, password)
      VALUES (:name, :password)');
    // $name =  $user->get_name();
    // $pwd = $user->get_password();
    $st->bindValue(':name', $user->get_name());
    $st->bindValue(':password', $user->get_password());
    $st->execute();
    return true;
  }
  public function autoLoginNewUser(){
    $session = SessionHelper::getInstance();
    $session->setParam('user_id', $this->db->lastInsertId());
  }

  static public function getUserById($id){
    //TODO: Add secure feature (filtring user input, etc)
    $db = self::connect();
    $st = $db->prepare('SELECT *
        FROM '.self::TBL_NAME.'
        WHERE id=:id');
    $st->bindvalue(':id',$id);
    $st->execute();
    $userData = $st->fetch(PDO::FETCH_ASSOC);
    $user = new UserModel($userData);

    return $user;
  }
  public function isRealUser(UserModel $user){
    $st = $this->db->prepare('SELECT *
        FROM '.self::TBL_NAME.'
        WHERE name=:name 
        AND password=:pwd');
    $st->bindValue(':name',$user->get_name());
    $st->bindValue(':pwd',$user->get_password());
    $st->execute();
    
    $userData = $st->fetch(PDO::FETCH_ASSOC);
    
    if($userData){
      $session = SessionHelper::getInstance();
      $session->setParam('user_id', $userData['id']);
    }
    return $userData;
  }
  public function forgot(){
    $session = SessionHelper::getInstance();
    $session->removeParam('user_id');
    $session->destroy();
  }
  public function getUserByName($name){
    $st = $this->db->prepare('SELECT *
        FROM '.self::TBL_NAME.'
        WHERE name='.$name);
    $st->execute();
    $userData = $st->fetch();
    if(!$userData){
      return false;
    }
    $user = new UserModel($userData);
    return $user;
  }

  static public function getCurrentUser(){
    $cUser = CurrentUserModel::getInstance();
    //Если юзер залогинен
    $session = SessionHelper::getInstance();

    if($session->getParam('user_id')){
      if($cUser->get_isGuest()){
        $user = self::getUserById($session->getParam('user_id'));
        $cUser->init($user);
        $cUser->set_isGuest(false);
      }
    }else{
      if(!$cUser->get_isGuest()){
        $cUser->set_isGuest(true);
      }
    }
    return $cUser;
  }

  static public function getManyUsersNameByIds($ids){
    $db = self::connect();
    $ids = implode(',', array_unique($ids));
    $st = $db->prepare('SELECT id, name 
                    FROM '.self::TBL_NAME.'
                    WHERE id IN('.$ids.')');
    $st->execute();
    $usersData = $st->fetchAll(PDO::FETCH_ASSOC);
    foreach ($usersData as $ud) {
      $userNames[$ud['id']] = $ud['name'];
    }
    return $userNames;
  }
}
?>